package com.yc.services;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.yc.config.AlipayConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class AlipayService {

    private final AlipayConfig alipayConfig;

    public String createQrCode(String outTradeNo, String totalAmount, String subject) throws AlipayApiException {
        // 验证金额格式
        if (!totalAmount.matches("^\\d+(\\.\\d{1,2})?$")) {
            throw new IllegalArgumentException("金额格式不正确，必须为数字且最多两位小数");
        }

        // 1. 创建AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getGateway(),
                alipayConfig.getAppId(),
                alipayConfig.getMerchantPrivateKey(),
                "json",
                "UTF-8",
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getSignType()
        );

        // 2. 创建预创建请求
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl(alipayConfig.getNotifyUrl());
//        request.setReturnUrl(alipayConfig.getReturnUrl());

        // 3. 构造请求参数（使用更安全的JSON构建方式）
        String bizContent = String.format("{" +
                "\"out_trade_no\":\"%s\"," +
                "\"total_amount\":\"%.2f\"," +  // 确保两位小数
                "\"subject\":\"%s\"," +
                "\"body\":\"沙箱测试订单\"," +
                "\"qr_code_timeout_express\":\"5m\"" +
                "}", outTradeNo, Double.parseDouble(totalAmount), subject);

        log.info("支付宝预创建请求参数: {}", bizContent);
        request.setBizContent(bizContent);

        // 4. 执行请求
        AlipayTradePrecreateResponse response = alipayClient.execute(request);

        if (response.isSuccess()) {
            String qrCodeUrl = response.getQrCode();
            log.info("支付宝二维码生成成功，订单号: {}, 二维码URL: {}", outTradeNo, qrCodeUrl);

            // 验证二维码URL格式
            if (qrCodeUrl == null || !qrCodeUrl.startsWith("https://")) {
                throw new RuntimeException("支付宝返回的二维码URL格式不正确: " + qrCodeUrl);
            }

            return qrCodeUrl;
        } else {
            String errorMsg = String.format("支付宝二维码生成失败，code=%s, msg=%s",
                    response.getSubCode(), response.getSubMsg());
            log.error(errorMsg);
            throw new RuntimeException(errorMsg);
        }
    }

    /**
     * 验证支付宝回调签名
     */
    public boolean verifySignature(Map<String, String> params) throws AlipayApiException {
        return AlipaySignature.rsaCheckV1(
                params,
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getCharset(),
                alipayConfig.getSignType()
        );
    }
}